#coding=utf-8
from django.views.generic.simple import direct_to_template
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect

def home(request):
    return direct_to_template (request, 'main.html')

def user_login(request):
    """
    Log user in 
    """
    if request.method == 'POST':
        user = authenticate(username=request.POST['username'], password=request.POST['password'])
      
        if user is not None:
            if user.is_active:
                login(request, user)
                try:
                    return HttpResponseRedirect(request.META.get('HTTP_REFERER', None))
                except KeyError:
                    return HttpResponseRedirect('/')
            else:
                return direct_to_template(request, 'invalid_login.html')
        else:
            return direct_to_template(request, 'invalid_login.html')
    return HttpResponseRedirect('/')
      
def user_logout(request):
    """
    Log users out and re-direct them to the main page.
    """
    logout(request)
    try:
        return HttpResponseRedirect(request.META.get('HTTP_REFERER', None))
    except KeyError:
        return HttpResponseRedirect('/')
